<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="theme-color" content="#1e3a8f">
    <title>📱 杂志图片管理器</title>
    
    <!-- PWA Meta Tags -->
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <meta name="apple-mobile-web-app-title" content="杂志管理器">
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #333;
            min-height: 100vh;
            overflow-x: hidden;
        }
        
        .app-container {
            max-width: 100vw;
            height: 100vh;
            display: flex;
            flex-direction: column;
            background: #fff;
        }
        
        /* 顶部导航栏 */
        .header {
            background: linear-gradient(135deg, #1e3a8f 0%, #3b82f6 100%);
            color: white;
            padding: 12px 16px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            position: sticky;
            top: 0;
            z-index: 100;
        }
        
        .header h1 {
            font-size: 18px;
            font-weight: 600;
            margin: 0;
        }
        
        .header-actions {
            display: flex;
            gap: 12px;
        }
        
        .header-btn {
            background: rgba(255,255,255,0.2);
            border: none;
            color: white;
            padding: 8px 12px;
            border-radius: 20px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .header-btn:hover {
            background: rgba(255,255,255,0.3);
            transform: translateY(-1px);
        }
        
        /* 搜索栏 */
        .search-container {
            padding: 16px;
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .search-box {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e2e8f0;
            border-radius: 25px;
            font-size: 16px;
            outline: none;
            transition: border-color 0.3s ease;
        }
        
        .search-box:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        
        /* 主要内容区域 */
        .main-content {
            flex: 1;
            overflow-y: auto;
            padding: 16px;
            background: #f8fafc;
        }
        
        /* 上传区域 */
        .upload-area {
            border: 3px dashed #cbd5e1;
            border-radius: 16px;
            padding: 40px 20px;
            text-align: center;
            background: white;
            margin-bottom: 20px;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        
        .upload-area.dragover {
            border-color: #3b82f6;
            background: #eff6ff;
            transform: scale(1.02);
        }
        
        .upload-icon {
            font-size: 48px;
            color: #94a3b8;
            margin-bottom: 16px;
        }
        
        .upload-text {
            font-size: 16px;
            color: #64748b;
            margin-bottom: 8px;
        }
        
        .upload-hint {
            font-size: 14px;
            color: #94a3b8;
        }
        
        /* 图片网格 */
        .images-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            gap: 12px;
            margin-top: 16px;
        }
        
        .image-item {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            cursor: pointer;
        }
        
        .image-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 16px rgba(0,0,0,0.15);
        }
        
        .image-item.selected {
            border: 3px solid #3b82f6;
            transform: scale(1.05);
        }
        
        .image-preview {
            width: 100%;
            height: 120px;
            object-fit: cover;
            background: #f1f5f9;
        }
        
        .image-info {
            padding: 8px;
        }
        
        .image-name {
            font-size: 12px;
            font-weight: 500;
            color: #1e293b;
            margin-bottom: 4px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .image-size {
            font-size: 10px;
            color: #64748b;
        }
        
        /* 底部操作栏 */
        .bottom-bar {
            background: white;
            border-top: 1px solid #e2e8f0;
            padding: 12px 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            bottom: 0;
        }
        
        .selected-count {
            font-size: 14px;
            color: #64748b;
        }
        
        .action-buttons {
            display: flex;
            gap: 8px;
        }
        
        .action-btn {
            padding: 8px 16px;
            border: none;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .btn-delete {
            background: #ef4444;
            color: white;
        }
        
        .btn-delete:hover {
            background: #dc2626;
        }
        
        .btn-share {
            background: #3b82f6;
            color: white;
        }
        
        .btn-share:hover {
            background: #2563eb;
        }
        
        /* 加载状态 */
        .loading {
            text-align: center;
            padding: 40px;
            color: #64748b;
        }
        
        .spinner {
            border: 3px solid #f3f4f6;
            border-top: 3px solid #3b82f6;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 16px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* 空状态 */
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #94a3b8;
        }
        
        .empty-icon {
            font-size: 64px;
            margin-bottom: 16px;
        }
        
        .empty-text {
            font-size: 16px;
            margin-bottom: 8px;
        }
        
        .empty-hint {
            font-size: 14px;
        }
        
        /* 安装提示 */
        .install-prompt {
            position: fixed;
            top: 20px;
            right: 20px;
            background: white;
            border-radius: 12px;
            padding: 16px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.15);
            z-index: 1000;
            max-width: 300px;
            transform: translateX(400px);
            transition: transform 0.3s ease;
        }
        
        .install-prompt.show {
            transform: translateX(0);
        }
        
        .install-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 8px;
            color: #1e293b;
        }
        
        .install-text {
            font-size: 14px;
            color: #64748b;
            margin-bottom: 12px;
        }
        
        .install-buttons {
            display: flex;
            gap: 8px;
        }
        
        .install-btn {
            flex: 1;
            padding: 8px 12px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .install-btn-primary {
            background: #3b82f6;
            color: white;
        }
        
        .install-btn-secondary {
            background: #f1f5f9;
            color: #64748b;
        }
        
        /* 文件输入隐藏 */
        #fileInput {
            display: none;
        }
        
        /* 响应式设计 */
        @media (max-width: 480px) {
            .images-grid {
                grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
                gap: 8px;
            }
            
            .image-preview {
                height: 100px;
            }
            
            .header h1 {
                font-size: 16px;
            }
            
            .header-btn {
                padding: 6px 10px;
                font-size: 12px;
            }
        }
        
        /* 使用说明 */
        .usage-guide {
            background: #fffbeb;
            border: 1px solid #f59e0b;
            border-radius: 12px;
            padding: 16px;
            margin: 16px;
            font-size: 14px;
            line-height: 1.6;
        }
        
        .usage-title {
            color: #92400e;
            font-weight: 600;
            margin-bottom: 8px;
        }
        
        .usage-step {
            color: #78350f;
            margin-bottom: 4px;
        }
    </style>
</head>
<body>
    <div class="app-container">
        <!-- 使用说明 -->
        <div class="usage-guide">
            <div class="usage-title">📱 手机使用步骤：</div>
            <div class="usage-step">1. 将此页面添加到主屏幕（浏览器菜单 → 添加到主屏幕）</div>
            <div class="usage-step">2. 从主屏幕图标打开，获得最佳体验</div>
            <div class="usage-step">3. 支持离线使用，无需网络连接</div>
        </div>
        
        <!-- 顶部导航 -->
        <header class="header">
            <h1>📱 杂志图片管理器</h1>
            <div class="header-actions">
                <button class="header-btn" onclick="selectFiles()">📤 上传</button>
                <button class="header-btn" onclick="refreshImages()">🔄 刷新</button>
            </div>
        </header>
        
        <!-- 搜索栏 -->
        <div class="search-container">
            <input type="text" class="search-box" placeholder="🔍 搜索图片..." id="searchBox">
        </div>
        
        <!-- 主要内容 -->
        <main class="main-content">
            <!-- 上传区域 -->
            <div class="upload-area" id="uploadArea" onclick="selectFiles()">
                <div class="upload-icon">📸</div>
                <div class="upload-text">点击或拖拽图片到这里上传</div>
                <div class="upload-hint">支持 JPG、PNG、GIF、WebP 格式</div>
            </div>
            
            <!-- 图片网格 -->
            <div class="images-grid" id="imagesGrid">
                <div class="loading" id="loading">
                    <div class="spinner"></div>
                    <div>正在加载图片...</div>
                </div>
            </div>
            
            <!-- 空状态 -->
            <div class="empty-state" id="emptyState" style="display: none;">
                <div class="empty-icon">📷</div>
                <div class="empty-text">还没有图片</div>
                <div class="empty-hint">点击上方上传区域添加图片</div>
            </div>
        </main>
        
        <!-- 底部操作栏 -->
        <div class="bottom-bar" id="bottomBar" style="display: none;">
            <div class="selected-count" id="selectedCount">已选择 0 张</div>
            <div class="action-buttons">
                <button class="action-btn btn-share" onclick="shareSelected()">📤 分享</button>
                <button class="action-btn btn-delete" onclick="deleteSelected()">🗑️ 删除</button>
            </div>
        </div>
    </div>
    
    <!-- 隐藏的文件输入 -->
    <input type="file" id="fileInput" accept="image/*" multiple onchange="handleFileSelect(event)">
    
    <!-- 安装提示 -->
    <div class="install-prompt" id="installPrompt">
        <div class="install-title">📱 安装应用</div>
        <div class="install-text">将图片管理器安装到主屏幕，随时使用！</div>
        <div class="install-buttons">
            <button class="install-btn install-btn-primary" onclick="installApp()">安装</button>
            <button class="install-btn install-btn-secondary" onclick="dismissInstall()">稍后</button>
        </div>
    </div>
    
    <script>
        // 全局变量
        let images = [];
        let selectedImages = new Set();
        let deferredPrompt = null;
        
        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeApp();
            setupEventListeners();
            checkInstallPrompt();
            loadSampleImages();
        });
        
        // 初始化应用
        function initializeApp() {
            setupDragAndDrop();
            setupSearch();
            checkStandaloneMode();
        }
        
        // 设置事件监听器
        function setupEventListeners() {
            // 搜索功能
            document.getElementById('searchBox').addEventListener('input', filterImages);
            
            // 图片选择
            document.addEventListener('click', function(e) {
                if (e.target.closest('.image-item')) {
                    toggleImageSelection(e.target.closest('.image-item'));
                }
            });
            
            // 长按选择
            let longPressTimer;
            document.addEventListener('touchstart', function(e) {
                if (e.target.closest('.image-item')) {
                    longPressTimer = setTimeout(() => {
                        toggleImageSelection(e.target.closest('.image-item'));
                    }, 500);
                }
            });
            
            document.addEventListener('touchend', function() {
                clearTimeout(longPressTimer);
            });
        }
        
        // 检查是否为独立模式（从主屏幕打开）
        function checkStandaloneMode() {
            if (window.matchMedia('(display-mode: standalone)').matches) {
                console.log('🏠 从主屏幕打开');
                document.querySelector('.usage-guide').style.display = 'none';
            }
        }
        
        // 加载示例图片
        function loadSampleImages() {
            // 优先从本地存储加载真实图片
            loadStoredImages();
            
            // 如果没有本地图片，显示示例图片
            if (images.length === 0) {
                const sampleImages = [
                    { name: '杂志封面.jpg', size: '2.5 MB', type: 'jpg' },
                    { name: '产品图片.png', size: '1.8 MB', type: 'png' },
                    { name: '宣传海报.gif', size: '3.2 MB', type: 'gif' },
                    { name: '文章配图.jpg', size: '1.5 MB', type: 'jpg' },
                    { name: '广告图片.png', size: '2.1 MB', type: 'png' },
                    { name: '背景图片.jpg', size: '3.8 MB', type: 'jpg' }
                ];
                
                images = sampleImages;
                setTimeout(() => {
                    displayImages(images);
                }, 1000);
            }
        }
        
        // 从本地存储加载图片
        function loadStoredImages() {
            try {
                const stored = localStorage.getItem('uploadedImages_v2');
                if (stored) {
                    const storedImages = JSON.parse(stored);
                    images = storedImages.map(img => ({
                        name: img.name,
                        size: formatFileSize(img.size),
                        type: img.type.split('/')[1] || 'jpg',
                        data: img.data,
                        isStored: true
                    }));
                    displayImages(images);
                    return true;
                }
            } catch (error) {
                console.error('加载本地图片失败:', error);
            }
            return false;
        }
        
        // 显示图片
        function displayImages(imagesToShow) {
            const grid = document.getElementById('imagesGrid');
            const loading = document.getElementById('loading');
            const emptyState = document.getElementById('emptyState');
            
            loading.style.display = 'none';
            
            if (imagesToShow.length === 0) {
                grid.innerHTML = '';
                emptyState.style.display = 'block';
                return;
            }
            
            emptyState.style.display = 'none';
            
            grid.innerHTML = imagesToShow.map(image => `
                <div class="image-item" data-name="${image.name}" onclick="toggleImageSelection(this)">
                    <img src="${image.data || 'https://via.placeholder.com/200x200/667eea/ffffff?text=' + (image.type || 'IMG').toUpperCase()}" 
                         alt="${image.name}" class="image-preview" loading="lazy"
                         style="${image.data ? 'object-fit: cover;' : ''}">
                    <div class="image-info">
                        <div class="image-name">${image.name}</div>
                        <div class="image-size">${image.size}</div>
                    </div>
                </div>
            `).join('');
        }
        
        // 搜索过滤
        function filterImages() {
            const searchTerm = document.getElementById('searchBox').value.toLowerCase();
            const filtered = images.filter(image => 
                image.name.toLowerCase().includes(searchTerm)
            );
            displayImages(filtered);
        }
        
        // 选择文件
        function selectFiles() {
            document.getElementById('fileInput').click();
        }
        
        // 处理文件选择
        function handleFileSelect(event) {
            const files = event.target.files;
            if (files.length > 0) {
                uploadFiles(files);
            }
        }
        
        // 拖拽上传
        function setupDragAndDrop() {
            const uploadArea = document.getElementById('uploadArea');
            
            uploadArea.addEventListener('dragover', function(e) {
                e.preventDefault();
                this.classList.add('dragover');
            });
            
            uploadArea.addEventListener('dragleave', function(e) {
                e.preventDefault();
                this.classList.remove('dragover');
            });
            
            uploadArea.addEventListener('drop', function(e) {
                e.preventDefault();
                this.classList.remove('dragover');
                const files = e.dataTransfer.files;
                if (files.length > 0) {
                    uploadFiles(files);
                }
            });
        }
        
        // 上传文件
        function uploadFiles(files) {
            const validFiles = Array.from(files).filter(file => 
                file.type.startsWith('image/')
            );
            
            if (validFiles.length === 0) {
                alert('请选择有效的图片文件');
                return;
            }
            
            // 显示上传进度
            showUploadProgress(validFiles.length);
            
            // 处理每个文件
            Promise.all(validFiles.map(file => processAndSaveImage(file)))
                .then(results => {
                    // 添加到现有图片列表
                    images = [...results, ...images];
                    displayImages(images);
                    
                    // 更新本地存储
                    updateLocalStorage();
                    
                    alert(`成功上传 ${validFiles.length} 张图片！`);
                })
                .catch(error => {
                    console.error('上传处理失败:', error);
                    alert('上传处理失败，请重试');
                });
        }
        
        // 处理并保存图片
        function processAndSaveImage(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                
                reader.onload = function(e) {
                    const imageData = {
                        name: file.name,
                        size: file.size,
                        type: file.type,
                        data: e.target.result,
                        uploadTime: new Date().toISOString()
                    };
                    
                    resolve({
                        name: file.name,
                        size: formatFileSize(file.size),
                        type: file.type.split('/')[1],
                        data: e.target.result,
                        isStored: true
                    });
                };
                
                reader.onerror = function() {
                    reject(new Error('读取文件失败'));
                };
                
                reader.readAsDataURL(file);
            });
        }
        
        // 更新本地存储
        function updateLocalStorage() {
            try {
                const imagesToStore = images.filter(img => img.isStored).map(img => ({
                    name: img.name,
                    size: img.size,
                    type: img.type,
                    data: img.data
                }));
                
                localStorage.setItem('uploadedImages_v2', JSON.stringify(imagesToStore));
                console.log('本地存储已更新');
            } catch (error) {
                console.error('更新本地存储失败:', error);
            }
        }
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
        }
        
        // 显示上传进度
        function showUploadProgress(count) {
            const uploadArea = document.getElementById('uploadArea');
            const originalContent = uploadArea.innerHTML;
            
            uploadArea.innerHTML = `
                <div class="loading">
                    <div class="spinner"></div>
                    <div>正在上传 ${count} 张图片...</div>
                </div>
            `;
            
            setTimeout(() => {
                uploadArea.innerHTML = originalContent;
            }, 2000);
        }
        
        // 切换图片选择
        function toggleImageSelection(element) {
            const imageName = element.dataset.name;
            
            if (selectedImages.has(imageName)) {
                selectedImages.delete(imageName);
                element.classList.remove('selected');
            } else {
                selectedImages.add(imageName);
                element.classList.add('selected');
            }
            
            updateBottomBar();
        }
        
        // 更新底部操作栏
        function updateBottomBar() {
            const bottomBar = document.getElementById('bottomBar');
            const selectedCount = document.getElementById('selectedCount');
            
            if (selectedImages.size > 0) {
                bottomBar.style.display = 'flex';
                selectedCount.textContent = `已选择 ${selectedImages.size} 张`;
            } else {
                bottomBar.style.display = 'none';
            }
        }
        
        // 删除选中的图片
        function deleteSelected() {
            if (selectedImages.size === 0) return;
            
            if (confirm(`确定要删除选中的 ${selectedImages.size} 张图片吗？`)) {
                // 从图片数组中删除选中的图片
                images = images.filter(img => !selectedImages.has(img.name));
                
                // 清空选中状态
                selectedImages.clear();
                updateBottomBar();
                
                // 更新显示
                displayImages(images);
                
                // 更新本地存储
                updateLocalStorage();
                
                alert('删除成功！');
            }
        }
        
        // 分享选中的图片
        function shareSelected() {
            if (selectedImages.size === 0) return;
            
            if (navigator.share) {
                navigator.share({
                    title: '杂志图片',
                    text: `分享了 ${selectedImages.size} 张图片`,
                    url: window.location.href
                });
            } else {
                alert('分享功能需要原生环境支持');
            }
        }
        
        // 刷新图片
        function refreshImages() {
            loadSampleImages();
        }
        
        // 设置搜索
        function setupSearch() {
            document.getElementById('searchBox').addEventListener('input', filterImages);
        }
        
        // 检查安装提示
        function checkInstallPrompt() {
            // 延迟显示安装提示
            setTimeout(() => {
                if (!window.matchMedia('(display-mode: standalone)').matches) {
                    document.getElementById('installPrompt').classList.add('show');
                }
            }, 3000);
        }
        
        // 安装应用
        function installApp() {
            if (deferredPrompt) {
                deferredPrompt.prompt();
                deferredPrompt.userChoice.then((choiceResult) => {
                    if (choiceResult.outcome === 'accepted') {
                        console.log('用户接受了安装');
                    }
                    deferredPrompt = null;
                });
            }
            document.getElementById('installPrompt').classList.remove('show');
        }
        
        // 关闭安装提示
        function dismissInstall() {
            document.getElementById('installPrompt').classList.remove('show');
        }
        
        // 监听安装事件
        window.addEventListener('beforeinstallprompt', (e) => {
            e.preventDefault();
            deferredPrompt = e;
        });
        
        // 监听显示模式变化
        window.addEventListener('DOMContentLoaded', () => {
            if (window.matchMedia('(display-mode: standalone)').matches) {
                console.log('🏠 从主屏幕打开');
                document.querySelector('.usage-guide').style.display = 'none';
            }
        });
    </script>
</body>
</html>